import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // 白名单
// 导航守卫
router.beforeEach(async(to, from, next) => {
  // 加载图标
  NProgress.start()

  // 浏览器选项卡标签名
  document.title = getPageTitle(to.meta.title)

  // 获取token
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()//加载图标
    } else {
      const hasGetUserInfo = store.getters.name//是否获取过用户信息
      if (hasGetUserInfo) {
        next() //放行
      } else {
        try {
          // 获取用户信息
          await store.dispatch('user/getInfo')
          //获取角色
          const roles=store.getters.roles
          //通过角色获取路由
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
          //添加到路由
          router.addRoutes(accessRoutes)
          next({ ...to, replace: true })
        } catch (error) {
          console.log(error)
          // 获取用户信息失败
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    // 无token
    // 是否是白名单
    if (whiteList.indexOf(to.path) !== -1) {
      // 如果是白名单则不需要登录也可以访问
      next()
    } else {
      // 跳转到登录页面
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // 关闭加载图标
  NProgress.done()
})
